# Praat script createPraatTests.praat
# Paul Boersma 2020-12-30

# This script extracts tests from C++ source code files
# in which Praat script snippets have been inserted
# between a "/*@praat" line and a "@*/" line,
# or after "//@praat " at the end of a line.
#
# For instance, the tests in the source code file sys/Formula.cpp
# are put into the new file test/sys/Formula.cpp.praat.

stopwatch

writeInfoLine: "Creating tests..."
numberOfTestFiles = 0
totalNumberOfTests = 0

folder$# = { "kar", "melder", "sys", "stat", "fon", "gram", "artsynth", "EEG", "main" }

for folder to size (folder$#)
	folder$ = folder$# [folder]
	files$# = fileNames$# ("../" + folder$ + "/*.cpp")
	for ifile to size (files$#)
		@createTest: folder$, files$# [ifile]
	endfor
	files$# = fileNames$# ("../" + folder$ + "/*.h")
	for ifile to size (files$#)
		@createTest: folder$, files$# [ifile]
	endfor
endfor

procedure createTest: .folder$, .file$
	.sourceFile$ = "../" + .folder$ + "/" + .file$
	.lines$# = readLinesFromFile$# (.sourceFile$)
	.targetFile$ = .folder$ + "/" + .file$ + ".praat"
	.numberOfTestsInThisFile = 0
	for .iline to size (.lines$#) - 2
		.line$ = .lines$# [.iline]
		if index (.line$, "/*@praat") or index (.line$, "//@praat")
			if .numberOfTestsInThisFile = 0
				writeFileLine: .targetFile$, "# File ", .folder$, "/", .file$, ".praat"
				appendFileLine: .targetFile$, "# Generated by test/createPraatTests.praat"
				;appendFileLine: .targetFile$, "# ", date$ ()   ; no date, because of GitHub
			endif
			.numberOfTestsInThisFile += 1
			appendFileLine: .targetFile$, ""
			if index (.line$, "//@praat")
				appendFileLine: .targetFile$, mid$ (.line$, index (.line$, "//@praat") + 9, 1000)
			else
				.numberOfLeadingTabs = index (.line$, "/*@praat")
				label again
				.iline += 1
				.line$ = .lines$# [.iline]
				goto finish index (.line$, "@*/")
				appendFileLine: .targetFile$, mid$ (.line$, .numberOfLeadingTabs + 1, 1000)
				goto again
			endif
		endif
		label finish
	endfor
	if .numberOfTestsInThisFile > 0
		appendFileLine: .targetFile$, newline$, "appendInfoLine: """, .targetFile$, """", ", "" OK"""
		appendInfoLine: "Written ", .numberOfTestsInThisFile, " tests into ", .targetFile$
		numberOfTestFiles += 1
		totalNumberOfTests += .numberOfTestsInThisFile
	endif
endproc

appendInfoLine: newline$, "Written ", numberOfTestFiles, " files with ", totalNumberOfTests, " tests in ", fixed$ (stopwatch, 3) , " seconds"
appendInfoLine: "OK"
